﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace RenderTheBetterEllipse
{
    class EllipseWithChild : BetterEllipse
    {
        UIElement child;

        public UIElement Child
        {
            set
            {
                if (this.child != null)
                {
                    this.RemoveVisualChild(this.child);
                    this.RemoveLogicalChild(this.child);
                }

                if ((this.child = value) != null)
                {
                    this.AddVisualChild(this.child);
                    this.AddLogicalChild(this.child);
                }
            }

            get
            {
                return this.child;
            }
        }

        protected override int VisualChildrenCount
        {
            get
            {
                return this.child != null ? 1 : 0;
            }
        }

        protected override Visual GetVisualChild(int index)
        {
            if (index > 0 || this.Child == null)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            return this.Child;
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            Size sizeDesired = new Size(0, 0);
            if (this.Stroke != null)
            {
                sizeDesired.Width += 2 * this.Stroke.Thickness;
                sizeDesired.Height += 2 * this.Stroke.Thickness;

                availableSize.Width = Math.Max(0, availableSize.Width - 2 * this.Stroke.Thickness);
                availableSize.Height = Math.Max(0, availableSize.Height - 2 * this.Stroke.Thickness);
            }

            if (this.Child != null)
            {
                this.child.Measure(availableSize);
                sizeDesired.Width += this.Child.DesiredSize.Width;
                sizeDesired.Height += this.Child.DesiredSize.Height;
            }

            return sizeDesired;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            if (this.Child != null)
            {
                Rect rect = new Rect(new Point((finalSize.Width - this.Child.DesiredSize.Width) / 2, (finalSize.Height - this.Child.DesiredSize.Height) / 2),
                    this.Child.DesiredSize);
                this.Child.Arrange(rect);
            }

            return finalSize;
        }
    }
}
